

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="深海火锅店">
  <meta name="keywords" content="">
  
    <meta name="description" content="Spring6学习04手写IOC 实现过程  创建子模块 创建测试类 创建两个注解 @Bean(代替@Component) @Di(代替@Autowired)   创建Bean容器接口ApplicationContext，定义方法，返回对象 实现Bean容器接口 返回对象 根据包规则加载bean    规则:扫描当前包及其子包里的所有类，判断类上是否有@Bean注解，如果有，则把这个类通过反射实例">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring6学习04">
<meta property="og:url" content="http://example.com/2023/03/14/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/Java/%E5%AD%A6%E4%B9%A0/%E6%A1%86%E6%9E%B6/Spring/Spring6/04_Spring6/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="Spring6学习04手写IOC 实现过程  创建子模块 创建测试类 创建两个注解 @Bean(代替@Component) @Di(代替@Autowired)   创建Bean容器接口ApplicationContext，定义方法，返回对象 实现Bean容器接口 返回对象 根据包规则加载bean    规则:扫描当前包及其子包里的所有类，判断类上是否有@Bean注解，如果有，则把这个类通过反射实例">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152335347.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152335120.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152335485.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152336525.png">
<meta property="article:published_time" content="2023-03-14T10:00:00.000Z">
<meta property="article:modified_time" content="2024-02-15T15:36:08.300Z">
<meta property="article:author" content="深海火锅店">
<meta property="article:tag" content="Spring6">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152335347.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Spring6学习04 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/background.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Spring6学习04"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-03-14 18:00" pubdate>
          2023年3月14日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          11k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          93 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Spring6学习04</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="Spring6学习04"><a href="#Spring6学习04" class="headerlink" title="Spring6学习04"></a>Spring6学习04</h1><h2 id="手写IOC"><a href="#手写IOC" class="headerlink" title="手写IOC"></a>手写IOC</h2><blockquote>
<p>实现过程</p>
<ol>
<li>创建子模块</li>
<li>创建测试类</li>
<li>创建两个注解<ol>
<li>@Bean(代替@Component)</li>
<li>@Di(代替@Autowired)</li>
</ol>
</li>
<li>创建Bean容器接口ApplicationContext，定义方法，返回对象</li>
<li>实现Bean容器接口<ol>
<li>返回对象</li>
<li>根据包规则加载bean</li>
</ol>
</li>
</ol>
<p><strong><code>规则:扫描当前包及其子包里的所有类，判断类上是否有@Bean注解，如果有，则把这个类通过反射实例化</code></strong></p>
</blockquote>
<h3 id="第一步，搭建项目"><a href="#第一步，搭建项目" class="headerlink" title="第一步，搭建项目"></a>第一步，搭建项目</h3><p><strong>创建两个注解，@Bean、@Di</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.lang.annotation.ElementType;<br><span class="hljs-keyword">import</span> java.lang.annotation.Retention;<br><span class="hljs-keyword">import</span> java.lang.annotation.RetentionPolicy;<br><span class="hljs-keyword">import</span> java.lang.annotation.Target;<br><br><span class="hljs-meta">@Target(ElementType.TYPE)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Bean &#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.lang.annotation.ElementType;<br><span class="hljs-keyword">import</span> java.lang.annotation.Retention;<br><span class="hljs-keyword">import</span> java.lang.annotation.RetentionPolicy;<br><span class="hljs-keyword">import</span> java.lang.annotation.Target;<br><br><span class="hljs-meta">@Target(ElementType.FIELD)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Di &#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>使用如下方式进行注入</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Bean</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserServiceImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">UserService</span> &#123;<br>    <span class="hljs-meta">@Di</span><br>    <span class="hljs-keyword">private</span> UserDao userDao;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>新建ApplicationContext接口</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">ApplicationContext</span> &#123;<br>    Object <span class="hljs-title function_">getBean</span><span class="hljs-params">(Class&lt;?&gt; clazz)</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>对接口进行实例化</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.HashMap;<br><span class="hljs-keyword">import</span> java.util.Map;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">AnnotationApplicationContext</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">ApplicationContext</span>&#123;<br>    <span class="hljs-comment">// 创建Map集合，用于存放Bean对象</span><br>    <span class="hljs-keyword">private</span> Map&lt;Class&lt;?&gt;,Object&gt; beanFactory=<span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 返回bean对象</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">getBean</span><span class="hljs-params">(Class&lt;?&gt; clazz)</span> &#123;<br>        <span class="hljs-keyword">return</span> beanFactory.get(clazz);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 创建有参构造方法，传递包路径，设置包扫描规则</span><br><span class="hljs-comment">     * 当前包及其子包，标注有<span class="hljs-doctag">@Bean</span>注解，把这个类通过反射实例化</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> basePackage 包路径</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">AnnotationApplicationContext</span><span class="hljs-params">(String basePackage)</span> &#123;<br>        <span class="hljs-comment">//</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<blockquote>
<p>为什么要写<code>AnnotationApplicationContext</code>的构造方法？</p>
<p>我们先来看看原本Spring是怎么写的</p>
</blockquote>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152335347.png" srcset="/img/loading.gif" lazyload alt="image-20230409104422741"></p>
<p><strong>以下是暂时的项目结构</strong></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152335120.png" srcset="/img/loading.gif" lazyload alt="image-20230409104055973"></p>
<h3 id="第二步，配置扫描规则"><a href="#第二步，配置扫描规则" class="headerlink" title="第二步，配置扫描规则"></a>第二步，配置扫描规则</h3><blockquote>
<p>用法应该如下所示</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Main</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">ApplicationContext</span> <span class="hljs-variable">context</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">AnnotationApplicationContext</span>(<span class="hljs-string">&quot;com.example&quot;</span>);<br>        <span class="hljs-type">Object</span> <span class="hljs-variable">bean</span> <span class="hljs-operator">=</span> context.getBean(UserDaoImpl.class);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<ol>
<li>将.替换成\ <code>（com.example）-&gt;（com\example）</code></li>
<li>获取包的(带盘符的)对路径 <code>（这里的绝对路径并非是当前类的绝对路径，而是编译后生成的target内的类路径）</code></li>
</ol>
<blockquote>
<p>由于转义字符的影响，所以得这么写</p>
<p>如果不放心，可以试着打印输出一下</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">String</span> <span class="hljs-variable">packagePath</span> <span class="hljs-operator">=</span> basePackage.replaceAll(<span class="hljs-string">&quot;\\.&quot;</span>, <span class="hljs-string">&quot;\\\\&quot;</span>);<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152335485.png" srcset="/img/loading.gif" lazyload alt="image-20230409112600074"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">AnnotationApplicationContext</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">ApplicationContext</span> &#123;<br>    <span class="hljs-comment">// 创建Map集合，用于存放Bean对象</span><br>    <span class="hljs-keyword">private</span> Map&lt;Class&lt;?&gt;, Object&gt; beanFactory = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    <span class="hljs-keyword">private</span> String rootPath;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 返回bean对象</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">getBean</span><span class="hljs-params">(Class&lt;?&gt; clazz)</span> &#123;<br>        <span class="hljs-keyword">return</span> beanFactory.get(clazz);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 创建有参构造方法，传递包路径，设置包扫描规则</span><br><span class="hljs-comment">     * 当前包及其子包，标注有<span class="hljs-doctag">@Bean</span>注解，把这个类通过反射实例化</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> basePackage 包路径</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">AnnotationApplicationContext</span><span class="hljs-params">(String basePackage)</span> &#123;<br>        <span class="hljs-comment">// com.example</span><br>        <span class="hljs-comment">// 1. 将.替换成\</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">packagePath</span> <span class="hljs-operator">=</span> basePackage.replaceAll(<span class="hljs-string">&quot;\\.&quot;</span>, <span class="hljs-string">&quot;\\\\&quot;</span>);<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 2. 获取包的绝对路径</span><br>            Enumeration&lt;URL&gt; urls = Thread.currentThread().getContextClassLoader().getResources(packagePath);<br>            <span class="hljs-comment">// 遍历枚举对象</span><br>            <span class="hljs-keyword">while</span> (urls.hasMoreElements()) &#123;<br>                <span class="hljs-type">URL</span> <span class="hljs-variable">url</span> <span class="hljs-operator">=</span> urls.nextElement();<br>                <span class="hljs-comment">// 斜杠会做url编码，所以要进行转码</span><br>                <span class="hljs-type">String</span> <span class="hljs-variable">filePath</span> <span class="hljs-operator">=</span> URLDecoder.decode(url.getFile(), <span class="hljs-string">&quot;UTF-8&quot;</span>);<br>                <span class="hljs-comment">// 获取包前面的路径部分，字符串截取</span><br>                rootPath=filePath.substring(<span class="hljs-number">0</span>,filePath.length()-packagePath.length());<br>                <span class="hljs-comment">// 包扫描</span><br>                loadBean(<span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(filePath));<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(e);<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 包扫描过程</span><br><span class="hljs-comment">     * 实例化</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">loadBean</span><span class="hljs-params">(File file)</span> &#123;<br>        <span class="hljs-comment">// 1.判断当前是否是文件夹</span><br>        <span class="hljs-comment">// 2.获取文件夹里的所有内容(文件夹、文件)</span><br>        <span class="hljs-comment">// 3.若文件夹里为空，直接返回</span><br>        <span class="hljs-comment">// 4.文件夹不为空，遍历文件夹所有内容</span><br>        <span class="hljs-comment">// 4.1遍历得到每个File对象，递归判断文件夹里是否还有文件夹...</span><br>        <span class="hljs-comment">// 4.2遍历得到File对象不是文件夹，是文件</span><br>        <span class="hljs-comment">// 4.3得到【包路径+类名称】部分-字符串截取</span><br>        <span class="hljs-comment">// 4.4判断当前类型是否是.class</span><br>        <span class="hljs-comment">// 4.5如果是.class类型，就把\替换成. 并 去掉后缀.class</span><br>        <span class="hljs-comment">// com.example.service.UserServiceImpl  因为只有获取类全路径名才能使用反射</span><br>        <span class="hljs-comment">// 4.6判断类上是否有注解@Bean，如果有，实例化过程</span><br>        <span class="hljs-comment">// 4.7把对象实例化之后，放到map集合beanFactory</span><br>        <span class="hljs-comment">// 小细节:如果有接口，就放接口class作为key，如果没有，就让自己class作为key</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="第三步，配置包扫描过程"><a href="#第三步，配置包扫描过程" class="headerlink" title="第三步，配置包扫描过程"></a>第三步，配置包扫描过程</h3><blockquote>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs">步骤<br></code></pre></td></tr></table></figure>

<ol>
<li>判断当前是否是文件夹</li>
<li>获取文件夹里的所有内容(文件夹、文件)</li>
<li>若文件夹里为空，直接返回</li>
<li>文件夹不为空，遍历文件夹所有内容<br>4.1 遍历得到每个File对象，递归判断文件夹里是否还有文件夹…<br>4.2 遍历得到File对象不是文件夹，是文件<br>4.3 得到【包路径+类名称】部分-字符串截取<br>4.4 判断当前类型是否是.class<br>4.5 如果是.class类型，就把\替换成. 并 去掉后缀.class <code>com.example.service.UserServiceImpl 因为只有获取类全路径名才能使用反射</code><br>4.6 判断类上是否有注解@Bean，如果有，实例化过程<br>4.7 把对象实例化之后，放到map集合beanFactory<br>小细节:如果有接口，就放接口class作为key，如果没有，就让自己class作为key</li>
</ol>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">AnnotationApplicationContext</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">ApplicationContext</span> &#123;<br>    <span class="hljs-comment">// 创建Map集合，用于存放Bean对象</span><br>    <span class="hljs-keyword">private</span> Map&lt;Class&lt;?&gt;, Object&gt; beanFactory = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    <span class="hljs-keyword">private</span> String rootPath;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 返回bean对象</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">getBean</span><span class="hljs-params">(Class&lt;?&gt; clazz)</span> &#123;<br>        <span class="hljs-keyword">return</span> beanFactory.get(clazz);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 创建有参构造方法，传递包路径，设置包扫描规则</span><br><span class="hljs-comment">     * 当前包及其子包，标注有<span class="hljs-doctag">@Bean</span>注解，把这个类通过反射实例化</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> basePackage 包路径</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">AnnotationApplicationContext</span><span class="hljs-params">(String basePackage)</span> &#123;<br>        <span class="hljs-comment">// com.example</span><br>        <span class="hljs-comment">// 1. 将.替换成\</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">packagePath</span> <span class="hljs-operator">=</span> basePackage.replaceAll(<span class="hljs-string">&quot;\\.&quot;</span>, <span class="hljs-string">&quot;\\\\&quot;</span>);<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 2. 获取包的绝对路径</span><br>            Enumeration&lt;URL&gt; urls = Thread.currentThread().getContextClassLoader().getResources(packagePath);<br>            <span class="hljs-comment">// 遍历枚举对象</span><br>            <span class="hljs-keyword">while</span> (urls.hasMoreElements()) &#123;<br>                <span class="hljs-type">URL</span> <span class="hljs-variable">url</span> <span class="hljs-operator">=</span> urls.nextElement();<br>                <span class="hljs-comment">// 斜杠会做url编码，所以要进行转码</span><br>                <span class="hljs-type">String</span> <span class="hljs-variable">filePath</span> <span class="hljs-operator">=</span> URLDecoder.decode(url.getFile(), <span class="hljs-string">&quot;UTF-8&quot;</span>);<br>                <span class="hljs-comment">// 获取包前面的路径部分，字符串截取</span><br>                rootPath=filePath.substring(<span class="hljs-number">0</span>,filePath.length()-packagePath.length());<br>                <span class="hljs-comment">// 包扫描</span><br>                loadBean(<span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(filePath));<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(e);<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 包扫描过程</span><br><span class="hljs-comment">     * 实例化</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">loadBean</span><span class="hljs-params">(File file)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-comment">// 1.判断当前是否是文件夹</span><br>        <span class="hljs-keyword">if</span>(file.isDirectory())&#123;<br>            <span class="hljs-comment">// 2.获取文件夹里的所有内容(文件夹、文件)</span><br>            File[] childrenFiles = file.listFiles();<br>            <span class="hljs-comment">// 3.若文件夹里为空，直接返回</span><br>            <span class="hljs-keyword">if</span>(childrenFiles==<span class="hljs-literal">null</span>||childrenFiles.length==<span class="hljs-number">0</span>)&#123;<br>                <span class="hljs-keyword">return</span>;<br>            &#125;<br>            <span class="hljs-comment">// 4.文件夹不为空，遍历文件夹所有内容</span><br>            <span class="hljs-keyword">for</span>(File child:childrenFiles)&#123;<br>                <span class="hljs-comment">// 4.1遍历得到每个File对象，递归判断文件夹里是否还有文件夹...</span><br>                <span class="hljs-keyword">if</span>(child.isDirectory())&#123;<br>                    <span class="hljs-comment">// 递归</span><br>                    loadBean(child);<br>                &#125;<span class="hljs-keyword">else</span>&#123;<br>                    <span class="hljs-comment">// 4.2遍历得到File对象不是文件夹，是文件</span><br>                    <span class="hljs-comment">// 4.3得到【包路径+类名称】部分-字符串截取</span><br>                    <span class="hljs-type">String</span> <span class="hljs-variable">pathWithClass</span> <span class="hljs-operator">=</span> child.getAbsolutePath().substring(rootPath.length() - <span class="hljs-number">1</span>);<br>                    <span class="hljs-comment">// 4.4判断当前类型是否是.class</span><br>                    <span class="hljs-keyword">if</span>(pathWithClass.contains(<span class="hljs-string">&quot;.class&quot;</span>))&#123;<br>                        <span class="hljs-comment">// 4.5如果是.class类型，就把\替换成. 并 去掉后缀.class</span><br>                        <span class="hljs-comment">// com.example.service.UserServiceImpl  因为只有获取类全路径名才能使用反射</span><br>                        <span class="hljs-type">String</span> <span class="hljs-variable">allName</span> <span class="hljs-operator">=</span> pathWithClass.replaceAll(<span class="hljs-string">&quot;\\\\&quot;</span>, <span class="hljs-string">&quot;.&quot;</span>).replace(<span class="hljs-string">&quot;.class&quot;</span>, <span class="hljs-string">&quot;&quot;</span>);<br>                        <span class="hljs-comment">// 4.6判断类上是否有注解@Bean，如果有，实例化过程</span><br>                        <span class="hljs-comment">// 4.6.1获取类的class对象</span><br>                        Class&lt;?&gt; clazz = Class.forName(allName);<br>                        <span class="hljs-comment">// 4.6.2判断，如果不是接口，则实例化</span><br>                        <span class="hljs-keyword">if</span>(!clazz.isInterface())&#123;<br>                            <span class="hljs-comment">// 4.6.3判断，类上是否有注解@Bean</span><br>                            <span class="hljs-type">Bean</span> <span class="hljs-variable">annotation</span> <span class="hljs-operator">=</span> clazz.getAnnotation(Bean.class);<br>                            <span class="hljs-keyword">if</span>(annotation!=<span class="hljs-literal">null</span>)&#123;<br>                                <span class="hljs-comment">// 类上@Bean有注解</span><br>                                <span class="hljs-comment">// 4.6.4实例化</span><br>                                <span class="hljs-type">Object</span> <span class="hljs-variable">instance</span> <span class="hljs-operator">=</span> clazz.getConstructor().newInstance();<br>                                <span class="hljs-comment">// 4.7把对象实例化之后，放到map集合beanFactory</span><br>                                <span class="hljs-comment">// 4.7.1小细节:如果有接口，就放接口class作为key，如果没有，就让自己class作为key</span><br>                                <span class="hljs-keyword">if</span>(clazz.getInterfaces().length&gt;<span class="hljs-number">0</span>)&#123;<br>                                    beanFactory.put(clazz.getInterfaces()[<span class="hljs-number">0</span>],instance);<br>                                &#125;<span class="hljs-keyword">else</span>&#123;<br>                                    beanFactory.put(clazz,instance);<br>                                &#125;<br>                            &#125;<br>                        &#125;<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="第四步，测试-Bean注解"><a href="#第四步，测试-Bean注解" class="headerlink" title="第四步，测试@Bean注解"></a>第四步，测试@Bean注解</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">UserDao</span> &#123;<br>    <span class="hljs-keyword">void</span> <span class="hljs-title function_">insert</span><span class="hljs-params">()</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Bean</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserDaoImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">UserDao</span> &#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">insert</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;userDao--insert&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">UserService</span> &#123;<br>    <span class="hljs-keyword">void</span> <span class="hljs-title function_">add</span><span class="hljs-params">()</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Bean</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserServiceImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">UserService</span> &#123;<br>    <span class="hljs-meta">@Di</span><br>    <span class="hljs-keyword">private</span> UserDao userDao;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">add</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;service--add&quot;</span>);<br>        <span class="hljs-comment">// TODO 调用dao的方法</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Main</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">ApplicationContext</span> <span class="hljs-variable">context</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">AnnotationApplicationContext</span>(<span class="hljs-string">&quot;com.example&quot;</span>);<br>        <span class="hljs-type">UserService</span> <span class="hljs-variable">userService</span> <span class="hljs-operator">=</span> (UserService) context.getBean(UserService.class);<br>        System.out.println(userService);<br>        userService.add();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="第五步，编写-Di注解属性注入逻辑"><a href="#第五步，编写-Di注解属性注入逻辑" class="headerlink" title="第五步，编写@Di注解属性注入逻辑"></a>第五步，编写@Di注解属性注入逻辑</h3><blockquote>
<p>实例化对象在beanFactory的map集合里<br>1.遍历beanFactory的map集合<br>2.获取map集合每个对象(value)，每个对象的属性获取到<br>3.遍历得到每个对象属性数组，得到每个属性<br>4.属性上是否有@Di的注解(如果是私有属性，需要设置为【可以设置值】)<br>5.如果有@Di的注解，把对象注入</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">AnnotationApplicationContext</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">ApplicationContext</span> &#123;<br>    <span class="hljs-comment">// 创建Map集合，用于存放Bean对象</span><br>    <span class="hljs-keyword">private</span> Map&lt;Class&lt;?&gt;, Object&gt; beanFactory = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>    <span class="hljs-keyword">private</span> String rootPath;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 返回bean对象</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">getBean</span><span class="hljs-params">(Class&lt;?&gt; clazz)</span> &#123;<br>        <span class="hljs-keyword">return</span> beanFactory.get(clazz);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 创建有参构造方法，传递包路径，设置包扫描规则</span><br><span class="hljs-comment">     * 当前包及其子包，标注有<span class="hljs-doctag">@Bean</span>注解，把这个类通过反射实例化</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> basePackage 包路径</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">AnnotationApplicationContext</span><span class="hljs-params">(String basePackage)</span> &#123;<br>        <span class="hljs-comment">// com.example</span><br>        <span class="hljs-comment">// 1. 将.替换成\</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">packagePath</span> <span class="hljs-operator">=</span> basePackage.replaceAll(<span class="hljs-string">&quot;\\.&quot;</span>, <span class="hljs-string">&quot;\\\\&quot;</span>);<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 2. 获取包的绝对路径</span><br>            Enumeration&lt;URL&gt; urls = Thread.currentThread().getContextClassLoader().getResources(packagePath);<br>            <span class="hljs-comment">// 遍历枚举对象</span><br>            <span class="hljs-keyword">while</span> (urls.hasMoreElements()) &#123;<br>                <span class="hljs-type">URL</span> <span class="hljs-variable">url</span> <span class="hljs-operator">=</span> urls.nextElement();<br>                <span class="hljs-comment">// 斜杠会做url编码，所以要进行转码</span><br>                <span class="hljs-type">String</span> <span class="hljs-variable">filePath</span> <span class="hljs-operator">=</span> URLDecoder.decode(url.getFile(), <span class="hljs-string">&quot;UTF-8&quot;</span>);<br>                <span class="hljs-comment">// 获取包前面的路径部分，字符串截取</span><br>                rootPath = filePath.substring(<span class="hljs-number">0</span>, filePath.length() - packagePath.length());<br>                <span class="hljs-comment">// 包扫描</span><br>                loadBean(<span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(filePath));<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(e);<br>        &#125;<br><br>        <span class="hljs-comment">// 属性注入</span><br>        loadDi();<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 属性注入</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">loadDi</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-comment">// 实例化对象在beanFactory的map集合里</span><br>        <span class="hljs-comment">// 1.遍历beanFactory的map集合</span><br>        Set&lt;Map.Entry&lt;Class&lt;?&gt;, Object&gt;&gt; entries = beanFactory.entrySet();<br>        <span class="hljs-keyword">for</span> (Map.Entry&lt;Class&lt;?&gt;, Object&gt; entry : entries) &#123;<br>            <span class="hljs-comment">// 2.获取map集合每个对象(value)，每个对象的属性获取到</span><br>            <span class="hljs-type">Object</span> <span class="hljs-variable">obj</span> <span class="hljs-operator">=</span> entry.getValue();<br>            <span class="hljs-comment">// 获取对象class</span><br>            Class&lt;?&gt; clazz = obj.getClass();<br>            <span class="hljs-comment">// 获取每个对象中的属性</span><br>            Field[] declaredFields = clazz.getDeclaredFields();<br>            <span class="hljs-comment">// 3.遍历得到每个对象属性数组，得到每个属性</span><br>            <span class="hljs-keyword">for</span> (Field field : declaredFields) &#123;<br>                <span class="hljs-comment">// 4.属性上是否有@Di的注解(如果是私有属性，需要设置为【可以设置值】)</span><br>                <span class="hljs-type">Di</span> <span class="hljs-variable">annotation</span> <span class="hljs-operator">=</span> field.getAnnotation(Di.class);<br>                <span class="hljs-keyword">if</span> (annotation != <span class="hljs-literal">null</span>) &#123;<br>                    <span class="hljs-comment">// 属性上有@Di注解</span><br>                    <span class="hljs-comment">// 如果是私有属性，需要设置为【可设置值】</span><br>                    field.setAccessible(<span class="hljs-literal">true</span>);<br>                    <span class="hljs-comment">// 5.如果有@Di的注解，把对象注入</span><br>                    System.out.println(<span class="hljs-string">&quot;类型:&quot;</span>+field.getType());<br>                    <span class="hljs-keyword">try</span> &#123;<br>                        field.set(obj, beanFactory.get(field.getType()));<br>                    &#125; <span class="hljs-keyword">catch</span> (IllegalAccessException e) &#123;<br>                        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(e);<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 包扫描过程</span><br><span class="hljs-comment">     * 实例化</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">loadBean</span><span class="hljs-params">(File file)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-comment">// 1.判断当前是否是文件夹</span><br>        <span class="hljs-keyword">if</span> (file.isDirectory()) &#123;<br>            <span class="hljs-comment">// 2.获取文件夹里的所有内容(文件夹、文件)</span><br>            File[] childrenFiles = file.listFiles();<br>            <span class="hljs-comment">// 3.若文件夹里为空，直接返回</span><br>            <span class="hljs-keyword">if</span> (childrenFiles == <span class="hljs-literal">null</span> || childrenFiles.length == <span class="hljs-number">0</span>) &#123;<br>                <span class="hljs-keyword">return</span>;<br>            &#125;<br>            <span class="hljs-comment">// 4.文件夹不为空，遍历文件夹所有内容</span><br>            <span class="hljs-keyword">for</span> (File child : childrenFiles) &#123;<br>                <span class="hljs-comment">// 4.1遍历得到每个File对象，递归判断文件夹里是否还有文件夹...</span><br>                <span class="hljs-keyword">if</span> (child.isDirectory()) &#123;<br>                    <span class="hljs-comment">// 递归</span><br>                    loadBean(child);<br>                &#125; <span class="hljs-keyword">else</span> &#123;<br>                    <span class="hljs-comment">// 4.2遍历得到File对象不是文件夹，是文件</span><br>                    <span class="hljs-comment">// 4.3得到【包路径+类名称】部分-字符串截取</span><br>                    <span class="hljs-type">String</span> <span class="hljs-variable">pathWithClass</span> <span class="hljs-operator">=</span> child.getAbsolutePath().substring(rootPath.length() - <span class="hljs-number">1</span>);<br>                    <span class="hljs-comment">// 4.4判断当前类型是否是.class</span><br>                    <span class="hljs-keyword">if</span> (pathWithClass.contains(<span class="hljs-string">&quot;.class&quot;</span>)) &#123;<br>                        <span class="hljs-comment">// 4.5如果是.class类型，就把\替换成. 并 去掉后缀.class</span><br>                        <span class="hljs-comment">// com.example.service.UserServiceImpl  因为只有获取类全路径名才能使用反射</span><br>                        <span class="hljs-type">String</span> <span class="hljs-variable">allName</span> <span class="hljs-operator">=</span> pathWithClass.replaceAll(<span class="hljs-string">&quot;\\\\&quot;</span>, <span class="hljs-string">&quot;.&quot;</span>).replace(<span class="hljs-string">&quot;.class&quot;</span>, <span class="hljs-string">&quot;&quot;</span>);<br>                        <span class="hljs-comment">// 4.6判断类上是否有注解@Bean，如果有，实例化过程</span><br>                        <span class="hljs-comment">// 4.6.1获取类的class对象</span><br>                        Class&lt;?&gt; clazz = Class.forName(allName);<br>                        <span class="hljs-comment">// 4.6.2判断，如果不是接口，则实例化</span><br>                        <span class="hljs-keyword">if</span> (!clazz.isInterface()) &#123;<br>                            <span class="hljs-comment">// 4.6.3判断，类上是否有注解@Bean</span><br>                            <span class="hljs-type">Bean</span> <span class="hljs-variable">annotation</span> <span class="hljs-operator">=</span> clazz.getAnnotation(Bean.class);<br>                            <span class="hljs-keyword">if</span> (annotation != <span class="hljs-literal">null</span>) &#123;<br>                                <span class="hljs-comment">// 类上@Bean有注解</span><br>                                <span class="hljs-comment">// 4.6.4实例化</span><br>                                <span class="hljs-type">Object</span> <span class="hljs-variable">instance</span> <span class="hljs-operator">=</span> clazz.getConstructor().newInstance();<br>                                <span class="hljs-comment">// 4.7把对象实例化之后，放到map集合beanFactory</span><br>                                <span class="hljs-comment">// 4.7.1小细节:如果有接口，就放接口class作为key，如果没有，就让自己class作为key</span><br>                                <span class="hljs-keyword">if</span> (clazz.getInterfaces().length &gt; <span class="hljs-number">0</span>) &#123;<br>                                    beanFactory.put(clazz.getInterfaces()[<span class="hljs-number">0</span>], instance);<br>                                &#125; <span class="hljs-keyword">else</span> &#123;<br>                                    beanFactory.put(clazz, instance);<br>                                &#125;<br>                            &#125;<br>                        &#125;<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Bean</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserServiceImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">UserService</span> &#123;<br>    <span class="hljs-meta">@Di</span><br>    <span class="hljs-keyword">private</span> UserDao userDao;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">add</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;service--add&quot;</span>);<br>        <span class="hljs-comment">// 调用dao的方法</span><br>        userDao.insert();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202402152336525.png" srcset="/img/loading.gif" lazyload alt="image-20230409150523624"></p>
<hr>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Spring6/" class="category-chain-item">Spring6</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Spring6/">#Spring6</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Spring6学习04</div>
      <div>http://example.com/2023/03/14/编程语言/Java/学习/框架/Spring/Spring6/04_Spring6/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>深海火锅店</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年3月14日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/03/14/%E6%8A%A5%E9%94%99%E8%AE%B0%E5%BD%95/SpringBoot/%E6%8B%A6%E6%88%AA%E5%99%A8/" title="拦截器">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">拦截器</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/03/13/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/Java/%E5%AD%A6%E4%B9%A0/%E6%A1%86%E6%9E%B6/Spring/Spring6/03_Spring6/" title="Spring6学习03">
                        <span class="hidden-mobile">Spring6学习03</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/EmoryHuang/BlogBeautify@1.1/DynamicRibbon.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
